package com.gensdai.leliang.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.classic.common.MultipleStatusView;
import com.gensdai.leliang.R;
import com.gensdai.leliang.adapter.StoreListRecyclerAdapter;
import com.gensdai.leliang.base.BaseActivity;
import com.gensdai.leliang.common.bean.OffLineStoreBean;
import com.gensdai.leliang.entity.parseBean.BaseParseList;
import com.gensdai.leliang.recyclerViewUtils.HorizontalDividerItemDecoration;
import com.gensdai.leliang.remoteInterface.RetrofitFactory;
import com.gensdai.leliang.retrofitUtils.BaseObserverList;
import com.gensdai.leliang.retrofitUtils.ModelFilteredFactory;
import com.gensdai.leliang.retrofitUtils.exception.APIException;
import com.gensdai.leliang.utils.BaseUtils;
import com.gensdai.leliang.view.Toaster;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.DefaultRefreshFooterCreater;
import com.scwang.smartrefresh.layout.api.DefaultRefreshHeaderCreater;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;
import com.trello.rxlifecycle2.android.ActivityEvent;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import retrofit2.HttpException;

/**
 * 线下体验店列表
 */
public class OfflineStoreListActivity extends BaseActivity {

    @BindView(R.id.storeList)
    RecyclerView storeList;
    LinearLayoutManager layoutManager;
    StoreListRecyclerAdapter adapter;
    @BindView(R.id.Multiplestatusview)
    MultipleStatusView Multiplestatusview;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;


    int pageNum = 0;
    int pageSize = 10;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);

        storeList.addItemDecoration(new HorizontalDividerItemDecoration.Builder(this).color(getResources().getColor(R.color.dividerColor)).size(2).build());
        storeList.setHasFixedSize(true);
        layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(OrientationHelper.VERTICAL);
        storeList.setLayoutManager(layoutManager);

        Multiplestatusview.setOnRetryClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Multiplestatusview.showContent();
                refreshLayout.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        refreshLayout.autoRefresh();
                    }
                },1000);
            }
        });

        initrefreshlayout();
    }

    private void initrefreshlayout() {
        refreshLayout.setDefaultRefreshHeaderCreater(new DefaultRefreshHeaderCreater() {
            @Override
            public RefreshHeader createRefreshHeader(Context context, RefreshLayout layout) {
                //指定为经典Header，默认是 贝塞尔雷达Header
                return new ClassicsHeader(context).setSpinnerStyle(SpinnerStyle.Translate);
            }
        });

        refreshLayout.setDefaultRefreshFooterCreater(new DefaultRefreshFooterCreater() {
            @Override
            public RefreshFooter createRefreshFooter(Context context, RefreshLayout layout) {
                //指定为经典Footer，默认是 BallPulseFooter
                return new ClassicsFooter(context).setSpinnerStyle(SpinnerStyle.Translate);
            }
        });

        refreshLayout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                getOfflineStoreList(true);
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                pageNum = 0;
                getOfflineStoreList(false);
            }
        });

        //设置滚动到最底部是否加载更多
        refreshLayout.setEnableAutoLoadmore(true);
        refreshLayout.setDisableContentWhenRefresh(true);
        refreshLayout.autoRefresh();
    }


    private void getOfflineStoreList(final boolean isloadmore) {

        if (!BaseUtils.isNetworkAvailable(this)) {
            //没有网络显示无网络
            Multiplestatusview.showNoNetwork();
            return;
        }
        Map<String, String> params = new HashMap<>();
        params.put("page", pageNum + "");
        params.put("pageNum", pageSize + "");
        ModelFilteredFactory
                .compose(RetrofitFactory.getInstance().API().GETOFFLINELIST(params)) //跟生命周期绑定一起)
                .compose(this.<BaseParseList<OffLineStoreBean>>bindUntilEvent(ActivityEvent.DESTROY))
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        //启动监听前的处理，一般用于显示dialog什么的
//                        Multiplestatusview.showLoading();
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserverList<OffLineStoreBean>(this) {

                    @Override
                    public void onSubscribe(@io.reactivex.annotations.NonNull Disposable d) {
                        //监听  用d判断是否注册  会优先执行
                        super.onSubscribe(d);
                        Log.d("OnDisposable", "OnDisposable");
                    }

                    @Override
                    public void onHandleError(int code, String message) {
                        //正确请求到数据 但是success为false
                        Toaster.showOneToast(code + ":" + message);

                        if (isloadmore) {

                        } else {
                            Multiplestatusview.post(new Runnable() {
                                @Override
                                public void run() {
                                    Multiplestatusview.showError();
                                }
                            });
                        }
                    }

                    @Override
                    public void onFailure(final Throwable e) {
                        super.onFailure(e);
                        if (e instanceof APIException) {
                            APIException exception = (APIException) e;
                            Toast.makeText(getApplicationContext(), exception.message, Toast.LENGTH_SHORT).show();
                        } else if (e instanceof UnknownHostException) {
                            Toast.makeText(getApplicationContext(), "请打开网络", Toast.LENGTH_SHORT).show();
                        } else if (e instanceof SocketTimeoutException) {
                            Toast.makeText(getApplicationContext(), "请求超时", Toast.LENGTH_SHORT).show();
                        } else if (e instanceof ConnectException) {
                            Toast.makeText(getApplicationContext(), "连接失败", Toast.LENGTH_SHORT).show();
                        } else if (e instanceof HttpException) {
                            Toast.makeText(getApplicationContext(), "请求异常" + ((HttpException) e).code(), Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(getApplicationContext(), "请求失败", Toast.LENGTH_SHORT).show();
                        }

                        if (isloadmore) {

                        } else {
                            Multiplestatusview.post(new Runnable() {
                                @Override
                                public void run() {
                                    Multiplestatusview.showError();
                                }
                            });
                        }
                    }

                    @Override
                    public void onHandleSuccess(List<OffLineStoreBean> t) {

                        if (isloadmore) {
                            attrloadmorelist(t);
                        } else {
                            initList(t);
                        }
                    }

                    @Override
                    public void onRequestEnd() {
                        super.onRequestEnd();
                        if (isloadmore) {
                            refreshLayout.finishLoadmore();
                        } else {
                            refreshLayout.finishRefresh();
                        }

                    }
                });
    }

    StoreListRecyclerAdapter.OnRecyclerViewItemClick click = new StoreListRecyclerAdapter.OnRecyclerViewItemClick() {
        @Override
        public void OnItemClick(OffLineStoreBean pos) {
            Intent it = new Intent(OfflineStoreListActivity.this, OfflineStoreInfoActivity.class);
            it.putExtra(OfflineStoreInfoActivity.EXTRA_SID,pos.shopId);
            startActivity(it);
        }

    };

    private void initList(List<OffLineStoreBean> t) {
        refreshLayout.finishRefresh();
        if (t != null && t.size() > 0) {
            if (t.size() == pageSize) {
                refreshLayout.setEnableLoadmore(true);
            } else {
                refreshLayout.setEnableLoadmore(false);
            }

            adapter = new StoreListRecyclerAdapter(this, t);
            storeList.setAdapter(adapter);
            adapter.setOnItemClick(click);
            //延迟3秒后显示内容页面
            Multiplestatusview.postDelayed(new Runnable() {
                @Override
                public void run() {
                    Multiplestatusview.showContent();
                }
            }, 500);
        }
    }

    private void attrloadmorelist(List<OffLineStoreBean> t) {
        refreshLayout.finishLoadmore();
        if (adapter != null) {
            if (t != null && t.size() > 0) {
                if (t.size() == pageSize) {
                    refreshLayout.setEnableLoadmore(true);
                } else {
                    refreshLayout.setEnableLoadmore(false);
                }
                adapter.addList(t);
            }

        }
    }

    @Override
    protected String getTitleStr() {
        return "线下体验店";
    }

    @Override
    protected boolean isShowBackButton() {
        return true;
    }

    @Override
    protected boolean isCustomTitle() {
        return false;
    }

    @Override
    protected int getLayoutResource() {
        return R.layout.activity_offline_store_list;
    }
}
